<?php
/**
 * $Id: JXwebPanel.php 1 2009-07-30 10:06:11Z hainam $
**/
require_once 'JXwebAPI.php';

class JXwebPanel extends JXwebAPI {
  function getVictimsInfo($range = 2) {
    
    $minLevel = $this->config['options']['attack_min'];
    $maxLevel = $this->config['options']['attack_max'];
    $maxTime = $this->config['options']['attack_time']*60;

    list($hx, $hy) = Tools::PosToXy($this->CityPos);
    $Victims = array();

    for ($k=0; $k<$range; $k++) {
      //First, list all square blocks around the homeland
      if ($k == 0) {
        $PosArray = array(array(0, 0));
      }
      else {
        $PosArray = array();
        for ($j=0; $j<2*$k; $j++) {
          $PosArray[] = array(-$k+$j, -$k);
          $PosArray[] = array($k, $j-$k);
          $PosArray[] = array($k-$j, $k);
          $PosArray[] = array(-$k, $k-$j);
        }
      }

      for ($j=0; $j<count($PosArray); $j++) {
        // set up the center
        $x = max(5, min(396, $hx + $PosArray[$j][0]*9));
        $y = max(5, min(396, $hy + $PosArray[$j][1]*9));

        // get cities in the block
        $result = ajax_GetMapUnitInfo($this->CityID, 3, Tools::XyToPos($x,$y));
        $MapUnitInfo = Tools::decode($result->data);

        //TODO: check if error go next

        foreach ($MapUnitInfo as $Unit) {
          if (
              ($Unit->Type == 5) &&
              ($Unit->Level >= $minLevel) &&
              ($Unit->Level <= $maxLevel) &&
              (Tools::TravelTime($this, $Unit->Pos) <= $maxTime) && 
              ($Unit->Pos != $this->CityPos) &&
              (empty($Unit->JuntaName) || $Unit->JuntaName != $this->config['UserInfo']['Organise']) &&
              !in_array($Unit->Pos, $this->config['options']['attack_exclude'])
          ) {
            $Victims[$Unit->Pos] = array($Unit->ID, 0);
            addLog(sprintf('%s (%s) time %d', $Unit->UserName, renderPos($Unit->Pos), Tools::TravelTime($this, $Unit->Pos)));
          }
        }
      }
    }
    
    return $Victims;
  }
  
  function getMailByID($ID, $MailType = 2) {
    $filename = 'data/mail/'. $this->user['username'] .'-'. $this->user['server'] .'-'. $ID;
    if (file_exists($filename)) {
      return file_get_contents($filename);
    }
    else {
      $result = ajax_GetFightMailByID($ID);
      if (strlen($result->data) > 1000)
        file_put_contents($filename, $result->data);
      return $result->data;
    }
  }
}